package com.ruoyi.web.controller.okr;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.Ztree;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.MakeOrderNumUtil;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.util.ShiroUtils;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.service.IOkrCycleService;
import com.ruoyi.system.service.IOkrInfoService;
import com.ruoyi.system.service.IOkrSynergyService;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.view.UserZtree;
import org.apache.commons.collections.map.LinkedMap;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * OKR信息Controller
 * 
 * @author OKR
 * @date 2020-04-28
 */
@Controller
@RequestMapping("/okr/info")
public class MyOkrInfoController extends BaseController
{
    private String prefix = "okr";

    @Autowired
    private IOkrInfoService okrInfoService;


    @Autowired
    private IOkrCycleService okrCycleService;


    @Autowired
    private IOkrSynergyService okrSynergyService;

    @Autowired
    private ISysDeptService deptService;


    /**
     * 加载协同树
     */
//    @RequiresPermissions("okr:info:synergyTree")
    @GetMapping("/okrSynergyTreeData")
    @ResponseBody
    public List<UserZtree> okrSynergyTreeData(OkrInfo okrInfo)
    {
        Long userId = ShiroUtils.getUserId();
        List<OkrSynergy> okrSynergyist = okrSynergyService.selectOkrSynergyByOkrId(okrInfo.getId());
        List<UserZtree> ztrees = deptService.queryOkrDeptTree(getUserIds(okrSynergyist));
        return ztrees;
    }


    /**
     * 获取用户userid清单
     * @param okrSynergyist
     * @return
     */
    public List<String> getUserIds(List<OkrSynergy> okrSynergyist){
        List<String> list = new ArrayList<>();
        for(OkrSynergy synergy : okrSynergyist){
            list.add(synergy.getUserId().toString());
        }
        return list;
    }


    @RequiresPermissions("okr:info:view")
    @GetMapping()
    public String info(ModelMap mmap)
    {
        List<OkrCycle> list = okrCycleService.selectOkrUseCycleList();
        mmap.put("cycleList", list);
        return prefix + "/info";
    }

    /**
     * 查询OKR信息列表
     */
    @RequiresPermissions("okr:info:list")
    @PostMapping("/list")
    @ResponseBody
    public List<OkrInfo> list(OkrInfo okrInfo,ModelMap mmap)
    {
        Long userId = ShiroUtils.getUserId();
        List<OkrInfo> list = okrInfoService.selectOkrInfoListByUserId(okrInfo,userId);
        return list;
    }



    /**
     * 查询OKR生效的周期列表
     */
    @RequiresPermissions("okr:cycle:useList")
    @PostMapping("/useList")
    @ResponseBody
    public List<OkrCycle> useList(OkrCycle okrCycle)
    {
        List<OkrCycle> list = okrCycleService.selectOkrCycleList(okrCycle);
        return list;
    }

    /**
     * 导出OKR信息列表
     */
    @RequiresPermissions("okr:info:export")
    @Log(title = "OKR信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(OkrInfo okrInfo)
    {
        List<OkrInfo> list = okrInfoService.selectOkrInfoList(okrInfo);
        ExcelUtil<OkrInfo> util = new ExcelUtil<OkrInfo>(OkrInfo.class);
        return util.exportExcel(list, "info");
    }

    /**
     * 新增OKR信息
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }




    /**
     * 新增保存OKR信息
     */
    @Transactional
    @RequiresPermissions("okr:info:add")
    @Log(title = "OKR信息", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(@RequestParam Map<String,Object> params,@RequestParam(required = false, value = "seasonItem[]") List<String> seasonItem,@RequestParam(required = false, value = "yearItem[]") List<String> yearItem)
    {
        SysUser user = ShiroUtils.getSysUser();
        String seasonObjective = (String)params.get("seasonObjective");
        String yearObjective = (String)params.get("yearObjective");
        List<OkrCycle> cycleList = okrCycleService.selectOkrUseCycleList();
        Long yearCycleId = getCycleId(cycleList,1);
        Long seasonCycleId = getCycleId(cycleList,0);
        if(!StringUtils.isEmpty(seasonObjective))   //判断季度OKR是否为空
        {
            saveOkrInfo(user.getUserId(),seasonObjective,seasonCycleId,seasonItem);
        }
        if(!StringUtils.isEmpty(yearObjective))   //判断年度OKR是否为空
        {
            saveOkrInfo(user.getUserId(),yearObjective,yearCycleId,yearItem);
        }
        return AjaxResult.success();
    }

    /**
     * 加工数据
     * @param userId
     * @param content
     * @param cycleId
     * @param item
     */
    @Transactional
    public void saveOkrInfo(Long userId,String content,Long cycleId,List<String> item)
    {
        String objRowId = new MakeOrderNumUtil().makeOrderNum();
        OkrInfo yearOkrInfo  = returnObjective(objRowId,userId,content,cycleId);
        //获取最大的OKR
        OkrInfo lastOkrInfo = okrInfoService.queryMaxOkrInfoByUserId(yearOkrInfo);
        int rowIndex = 0;
        if(lastOkrInfo!=null)
        {
            rowIndex = Integer.parseInt(lastOkrInfo.getRowCode());
        }
        int rowCode = rowIndex+1;
        yearOkrInfo.setRowCode(rowCode+"");
        //存储年度目标
        okrInfoService.insertOkrInfo(yearOkrInfo);
        int row = 1;
        //检查是否存在KR--如果存在--》存储对应的KR
        for(int i=0;i<item.size();i++){
            OkrInfo yearKeyResult  = returnKeyResult(objRowId,userId,item.get(i),cycleId);
            row+=i;
            yearKeyResult.setRowCode(row+"");
            okrInfoService.insertOkrInfo(yearKeyResult);
        }
    }

    /**
     *  构造Objective
     * @param objRowId
     * @param userId
     * @param objective
     * @param cycleId
     * @return
     */
    public OkrInfo returnObjective(String objRowId,Long userId,String objective,Long cycleId){
        OkrInfo okrInfo  = new OkrInfo();
        okrInfo.setRowId(objRowId);
        okrInfo.setUserId(userId);
        okrInfo.setContent(objective);
        okrInfo.setCycleId(cycleId);
        return okrInfo;
    }

    /**
     *  构造KeyResult
     * @param parentId
     * @param userId
     * @param objective
     * @param cycleId
     * @return
     */
    public OkrInfo returnKeyResult(String parentId,Long userId,String objective,Long cycleId){
        OkrInfo okrInfo  = new OkrInfo();
        String rowId = new MakeOrderNumUtil().makeOrderNum();
        okrInfo.setRowId(rowId);
        okrInfo.setParentId(parentId);
        okrInfo.setUserId(userId);
        okrInfo.setContent(objective);
        okrInfo.setCycleId(cycleId);
        okrInfo.setRowType(1L);
        return okrInfo;
    }
    /**
     * 获取生效的OKR类型
     * @param cycleList  生效数据
     * @param type 1为年度，0为季度
     * @return
     */
    public Long getCycleId(List<OkrCycle> cycleList,int type){
        Long cycleId = cycleList.get(0).getId();
        for(int i=0;i<cycleList.size();i++){
            OkrCycle cycle = cycleList.get(i);
            if(cycle.getCycleType()==type)
            {
                cycleId = cycle.getId();
            }
        }
        return cycleId;
    }

    /**
     * 修改OKR信息
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap)
    {
        OkrInfo okrInfo = okrInfoService.selectOkrInfoById(id);
        mmap.put("okrInfo", okrInfo);
        return prefix + "/edit";
    }

    /**
     * 修改保存OKR信息
     */
    @RequiresPermissions("okr:info:edit")
    @Log(title = "OKR信息", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(OkrInfo okrInfo)
    {
        updateSynergy(okrInfo);  //OKR  协同关系   处理
        return toAjax(okrInfoService.updateOkrInfo(okrInfo));
    }

    /**
     * 更新协同关系
     * @param okrInfo
     */
    @Transactional
    public void updateSynergy(OkrInfo okrInfo){

        //检测是否有勾选协同关系
        String userIds = okrInfo.getSynergyUsers();
        if(!StringUtils.isEmpty(userIds))
        {
            String[] userArr = userIds.split(",");
            //清理OKR对应关系，后续程序进行插入--后期可以改成redis存储关系
            okrSynergyService.deleteOkrSynergyByOkrId(okrInfo.getId());
            for(int i=0;i<userArr.length;i++){
                Long okrId = okrInfo.getId();
                Long userId = Long.parseLong(userArr[i]);
                OkrSynergy okrSynergy = new OkrSynergy();
                okrSynergy.setOkrId(okrId);
                okrSynergy.setUserId(userId);
                //正式上线前需要改成批量插入《待修改标记位》
                okrSynergyService.insertOkrSynergy(okrSynergy);
            }
        }
    }

    /**
     * 删除OKR信息
     */
    @RequiresPermissions("okr:info:remove")
    @Log(title = "OKR信息", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(okrInfoService.deleteOkrInfoByIds(ids));
    }
}
